<template>
  <div
    class="echarts-content"
    :style="`${showLegend ? '' : 'width: 280px'}`"
    :id="props.id"
  ></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { nextTick, onMounted, ref, watch, defineEmits } from 'vue'
const bgImg = new URL(`/src/assets/images/pie-circle.svg`, import.meta.url).href
interface EchartDataItem {
  value: number
  name: string
}
defineOptions({
  name: 'GearPie'
})
const emit = defineEmits(['fresh'])
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  pieData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  },
  showLegend: {
    type: Boolean,
    default: true
  }
})
const showLegend = ref(props.showLegend)
watch(
  () => props.pieData,
  (val) => {
    drawChart()
  },
  {
    deep: true
  }
)
onMounted(async () => {
  nextTick(() => {
    drawChart()
  })
})
const legendDataType = (data: Array<EchartDataItem>, type: string) => {
  // 将legend独立出来做样式调整
  let total: number = 0
  data.forEach((item: any) => {
    total += Number(item.value)
  })
  function legendDataA() {
    let legendData: any = []
    let top: number = 1
    let left: number = 50
    for (let i = 0; i < data.length; i++) {
      let item: EchartDataItem = data[i]
      let legendItemData: Array<String> = [item.name]
      if (i !== 0) top += 10
      let obj = {
        // orient: 'vertical',
        left: `${left}%`,
        top: `${top}%`,
        height: '60%',
        itemWidth: 14,
        itemHeight: 14,
        tooltip: {
          show: false // 禁用图例的鼠标移入提示框
        },
        selectedMode: true, //取消图例上的点击事件
        data: legendItemData,
        formatter: function (name: string) {
          // 格式化文本显示
          let target = item.value
          target =
            Number(target) < 1000 ? Number(target) : `${(Number(target) / 10000).toFixed(2)}万`
          let percent: number = Math.floor((item.value * 100) / total)
          var arr = ['{a|' + name + '}', '{b|' + target + '}', '{c|(' + percent + '%)}']
          return arr.join('')
        },
        textStyle: {
          // 对应文本样式
          padding: [0, 0, 0, 5],
          rich: {
            a: {
              fontSize: 14,
              width: 150,
              color: '#5A6672',
              fontFamily: 'PingFangSC'
            },
            b: {
              fontSize: 14,
              width: 60,
              color: '#1D2129',
              fontFamily: 'PingFangSC'
            },
            c: {
              fontSize: 12,
              width: 38,
              color: '#5A6672',
              fontFamily: 'PingFangSC'
            }
          }
        }
      }
      legendData.push(obj)
    }
    return props.showLegend ? legendData : { show: false }
  }
  function legendDataB() {
    let left = 20
    let legendData = {
      orient: 'vertical',
      left: `${left}%`,
      top: `center`,
      // height: '60%',
      itemWidth: 14,
      itemHeight: 14,
      tooltip: {
        show: false // 禁用图例的鼠标移入提示框
      },
      selectedMode: true, //取消图例上的点击事件
      // data: legendItemData,
      formatter: function (name: string) {
        // 格式化文本显示
        let item = data.filter((item) => {
          return item.name == name
        })[0]
        console.log('item: ', item)
        let target = item?.value
        console.log('target: ', target)
        console.log('total: ', total)
        let percent: number = Math.floor((item.value * 100) / total)
        var arr = ['{a|' + name + '}', '{b|' + target + '}', '{c|(' + percent + '%)}']
        return arr.join('')
      },
      textStyle: {
        // 对应文本样式
        padding: [0, 0, 0, 5],
        rich: {
          a: {
            fontSize: 14,
            width: 100,
            color: '#5A6672',
            fontFamily: 'PingFangSC'
          },
          b: {
            fontSize: 14,
            width: 60,
            color: '#1D2129',
            fontFamily: 'PingFangSC'
          },
          c: {
            fontSize: 12,
            width: 38,
            color: '#5A6672',
            fontFamily: 'PingFangSC'
          }
        }
      }
    }
    console.log('legendData: ', legendData)
    return legendData
  }
  switch (type) {
    case 'A':
      legendDataRef.value = legendDataA()
      return legendDataA()
    case 'B':
      return legendDataB()
  }
}
const legendDataRef = ref()
const drawChart = () => {
  let data = props.pieData.data
  let options = {
    color: ['#BE5BED', '#63C072', '#FFD12C', '#4BC3E9', '#5473E8', '#FF7D61'], // 调色盘
    tooltip: {
      trigger: 'item'
    },
    animation: true, // 动画
    legend: legendDataType(data, 'A'),
    graphic: [
      {
        type: 'image',
        // right: 'center',
        left: 0,
        bottom: 'center',
        z: 0,
        bounding: 'all',
        style: {
          image: bgImg,
          width: 240,
          height: 240
        }
      }
    ],
    series: [
      {
        name: '征集方式分类',
        type: 'pie',
        radius: showLegend.value ? ['55%', '70%'] : ['65%', '80%'],
        center: ['120px', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          fontSize: 16,
          fontWeight: 'bold',
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data
      }
    ]
  }
  //检测是否已经存在echarts实例，如果不存在，则不再去初始化
  let chart = echarts.getInstanceByDom(document.getElementById(props.id) as HTMLElement)
  //如果为空 则正常进行渲染 反之 不再进行初始化
  if (chart == null) {
    chart = echarts.init(document.getElementById(props.id))
  }

  chart.setOption(options)
  chart.on('click', (params) => {
    console.log('params: ', params)
    freshSecondData(params.name)
  })
  chart.on('legendselectchanged', function (params: any) {
    // console.log('params: ', params)
    // let keys = Object.keys(params.selected)
    // let selected = {}
    // keys.forEach((it) => {
    //   selected[it] = true
    // })
    // legendDataRef.value.forEach((item) => {
    //   item.selected = selected
    // })
    // chart.setOption({
    //   legend: legendDataRef.value
    // })
    // freshSecondData(params.name)
  })
}
const freshSecondData = (name: any) => {
  console.log(props.id)
  if (props.id == 'colGearPieFirst' && clickName.value != name) emit('fresh', name)
  clickName.value = name
}
const clickName = ref('')
</script>

<style lang="scss" scoped>
.echarts-content {
  // width: 500px;
  height: 320px;
}
</style>
